package com.mediacloud.app.newsmodule.fragment.audio.live

import android.os.Bundle
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.audio.live.AudioLiveColumnHomeProgrammeListAdapter
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.RxUtils
import com.mediacloud.app.util.ClickUtils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.read.AudioFloatManager
import kotlinx.android.synthetic.main.fragment_program_home_programme_list.*
import org.json.JSONArray
import org.json.JSONObject
import java.util.*

/**
 * 广播  节目单 主页列表
 */
class AudioLiveColumnHomeProgrammeListFragment : HqyNavFragment(), OnRefreshLoadMoreListener,AudioFloatManager.OnCloseListener {
    private val mDataList: MutableList<ArticleItem> = ArrayList()
    private var mProgrammeAdapter: AudioLiveColumnHomeProgrammeListAdapter? = null
    private var mPageIndex: Int = 1
    private var PAGE_SIZE: Int = 20
    private var mRcatalogid:String?=null
    private var programArticleItem:ArticleItem?=null

    companion object {
        fun newInstance(title: String? = "" , articleItem: ArticleItem? ): AudioLiveColumnHomeProgrammeListFragment {
            val fragment = AudioLiveColumnHomeProgrammeListFragment()
            val bundle = Bundle()
            bundle.putString("title", title)
            bundle.putParcelable("data",articleItem)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_program_home_programme_list
    }

    override fun initArgs() {
        super.initArgs()
        programArticleItem=arguments?.getParcelable("data")
        try {
            val param: JSONObject? = JSONObject(programArticleItem?.appCustomParams)
            mRcatalogid=param?.optJSONObject("movie")?.optString("Rcatalogid")
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    override fun initView() {
        loadingView = mLoadingView
        initStateView()
    }

    override fun initOther() {
        super.initOther()
        AudioFloatManager.getInstance(requireContext()).addCloseListener(this)
        showStateView(TYPE_LOADING, false)
        initRecyclerView()
        initListener()
    }

    private fun initRecyclerView() {
        mProgrammeAdapter = AudioLiveColumnHomeProgrammeListAdapter(mDataList)
        recyclerview.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(context,true)
        mProgrammeAdapter?.bindToRecyclerView(recyclerview)
    }

    private fun initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(this)
        loadingView.setOnClickListener {
            if (TYPE_LOADING != currentState) {
                showStateView(TYPE_LOADING, false)
                onRefresh()
            }
        }
        mProgrammeAdapter?.setOnItemClickListener { adapter, view, position ->
            ClickUtils.delayClickable(view)
            mProgrammeAdapter?.data?.get(position)?.let {
                NewsItemClickUtils.OpenItemNewsHandle(requireContext(),
                        it.getType(), it, CatalogItem())
            }
            mProgrammeAdapter?.selectPosition = position
            mProgrammeAdapter?.notifyDataSetChanged()
        }

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        onRefresh()

    }

    private fun onRefresh() {
        mPageIndex = 1
        getList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        onLoadMore()
    }

    private fun onLoadMore() {
        mPageIndex++
        getList()
    }

    private var isFirstLoadingData = true

    override fun onResume() {
        super.onResume()

        if (isAdded && hadChoosed) {
            if (isFirstLoadingData) {
                onRefresh()
                isFirstLoadingData = false
            }
        }
    }

    override fun choosed() {
        super.choosed()
        if (activity != null) {
            if (isFirstLoadingData) {
                onRefresh()
                isFirstLoadingData = false
            }
        }
    }


    fun setEnableRefresh(enable: Boolean) {
        if (activity == null || requireActivity().isFinishing) {
            return
        }
        refreshLayout.setEnableRefresh(enable)
    }

    fun getList() {
        val map: MutableMap<String, Any> = HashMap()
        map["catalog_id"] = "${mRcatalogid?:""}"
        map["page"] = mPageIndex
        map["perPage"] = PAGE_SIZE

        DataInvokeUtil.getZiMeiTiApi().getArticleCmsList(map)
                .compose(RxUtils.schedulersTransformer())
                .subscribe({
                    if (activity == null || requireActivity().isFinishing) {
                        return@subscribe
                    }

                    var isHasNextPage: Boolean = false
                    if (mPageIndex == 1) {
                        refreshLayout.finishRefresh()
                        mDataList.clear()
                        mProgrammeAdapter?.replaceData(mDataList)
                    } else {
                        refreshLayout.finishLoadMore()
                    }
                    val tempList:MutableList<ArticleItem> = ArrayList()
                    if (it.optBoolean("state")) {

                        var data: JSONObject?  = it.optJSONObject("data")
                        val meta: JSONArray? = data?.optJSONArray("meta")

                        val paging:JSONObject? = data?.optJSONObject("paging")

                        paging?.let {
                            if (mPageIndex == 1) {
                                mProgrammeAdapter?.maxCount=it.optInt("total", 0)
                            }
                            isHasNextPage = it.optInt("lastPage", 1) != it.optInt("currentPage", 1)
                        }

                        try {
                            meta?.let {
                                for (i in 0 until it.length()) {
                                    val item = ArticleItem.parse(meta.optJSONObject(i))
                                    tempList.add(item)
                                    AudioFloatManager.getInstance(requireContext()).article?.let {
                                        if (it.equals(item)){
                                            mProgrammeAdapter?.selectPosition=i
                                        }
                                    }
                                }
                            }
                        }catch (e:Exception){
                            e.printStackTrace()
                        }
                    }

                    mProgrammeAdapter?.addData(tempList)
                    if (mPageIndex == 1) {
                        if (mProgrammeAdapter?.data == null || mProgrammeAdapter?.data?.size == 0) {
                            showStateView(BaseBackActivity.TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    }
                    if (isHasNextPage) {
                        refreshLayout.setEnableLoadMore(true)
                        refreshLayout.setNoMoreData(false)
                    } else {
                        refreshLayout.setNoMoreData(true)
                    }
                },{
                    if (activity == null || requireActivity().isFinishing) {
                        return@subscribe
                    }
                    if (mPageIndex == 1) {
                        refreshLayout.finishRefresh()
                        if (it != null && (mProgrammeAdapter?.data == null || mProgrammeAdapter?.data?.size == 0)) {
                            showStateView(BaseBackActivity.TYPE_NET_NOT_GIVE_FORCE, false)
                            it.printStackTrace()
                        } else if (mProgrammeAdapter?.data == null || mProgrammeAdapter?.data?.size == 0) {
                            showStateView(BaseBackActivity.TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    } else {
                        refreshLayout.finishLoadMore()
                        if (mPageIndex > 1) {
                            mPageIndex--
                        }
                    }
                },{

                },{
                    compositeDisposable.add(it)
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        AudioFloatManager.getInstance(requireContext()).removeCloseListener(this)

    }
    override fun onEasyFloatClose() {
        if (activity == null || requireActivity().isFinishing) {
            return
        }
        mProgrammeAdapter?.selectPosition=-1
        mProgrammeAdapter?.notifyDataSetChanged()
    }

}